package com.david.http.http.convert

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.Call
import retrofit2.CallAdapter
import java.lang.reflect.Type

class ResponseCallAdapter(
    private val responseType: Type
) : CallAdapter<Any, Flow<Any>> {
    override fun adapt(call: Call<Any>): Flow<Any> {
        return flow {
            val response = call.clone().execute()
            if (response.isSuccessful) {
                val result = response.body()
                if (result == null) {
                    throw Exception("${call.request().url} 返回body为空")
                } else {
                    emit(result)
                }
            } else {
                throw Exception("${call.request().url} HTTP ${response.code()} ${response.message()}")
            }
        }.catch {
            throw it
            //throwOtherException(it, call.request().url.toString())
        }.flowOn(Dispatchers.IO)
    }

    override fun responseType() = responseType
}